package com.time.company.components.login;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.servermodel.BasicBean;
import com.time.company.utils.MobileUtils;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.lang.ref.WeakReference;

/**
 * Created by Bing on 2017/11/27.
 * E-mail is tx16bing@163.com
 */

public class ForgetPsdNextActivity extends BaseActivity{

    private static final String EXTRA_TELEPHONE = "extra_telephone";
    private static final String EXTRA_PSD = "extra_psd";
    private static final String EXTRA_FLAG = "extra_flag";

    private static final int GET_VALIDATION_TIME = 4;
    private static final int GET_VALIDATION_TIME_OUT = 5;

    private String curTelephone, curPsd;

    // Views
    private EditText etCode;
    private Button btnConfirm;
    private TextView tvCountDown, tvSendAgain;

    private Request request;

    private MyHandler codeHandler = new MyHandler(this);

    public static void start(Activity activity, int requestCode, String telephone, String psd, String flag) {
        Intent intent = new Intent(activity, ForgetPsdNextActivity.class);
        intent.putExtra(EXTRA_TELEPHONE, telephone);
        intent.putExtra(EXTRA_PSD, psd);
        intent.putExtra(EXTRA_FLAG, flag);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_psd_next, getString(R.string.activity_forget_title));
        curTelephone = getIntent().getStringExtra(EXTRA_TELEPHONE);
        curPsd = getIntent().getStringExtra(EXTRA_PSD);
        assignViews();

        requestCode(MobileUtils.getCodeType(getString(R.string.verify_code_default)));
    }

    private void assignViews() {
        etCode = findView(R.id.et_forget_valid_code);
        btnConfirm = findView(R.id.btn_forget_confirm);
        tvCountDown = findView(R.id.tv_forget_count_down);
        tvSendAgain = findView(R.id.tv_forget_send_code_again);
        tvSendAgain.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvSendAgain.getPaint().setAntiAlias(true);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etCode.getText().toString().trim())){
                    ToastUtils.showShort(getString(R.string.please_input_code));
                    return;
                }
                requestModify();
            }
        });
        tvSendAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestCode(MobileUtils.getCodeType(getString(R.string.verify_code_default)));
            }
        });
    }

    private void requestCode(String type) {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress(), RequestMethod.POST);
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_sendCode));
            parameters.setTelephone(curTelephone);
            parameters.setUserType(getString(R.string.user_type_company));
            parameters.setType(type);
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, 100,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    private void requestModify() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress(), RequestMethod.POST);
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_forgetPasswordForCompany));
            parameters.setTelephone(curTelephone);
            parameters.setPassword(curPsd);
            parameters.setCode(etCode.getText().toString().trim());
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            Logger.e("Parameters " + new Gson().toJson(parameters));
            WebServerManager.getInstance().add(this, request, this, 101,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }


    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;
        if (basicBean.isSuccess()){
            if (what == 100){
                // 获取验证码成功
                countDown();
                ToastUtils.showShort(getString(R.string.attention_to_get_code));
            }else {
                // 101
                ToastUtils.showShort("重置密码成功");
                String flag = getIntent().getStringExtra(EXTRA_FLAG);
                if (TextUtils.equals(flag, getString(R.string.psd_forget_flag))){
                    LoginActivity.start(this);
                }else {
                    setResult(RESULT_OK);
                    finish();
                }
            }

        }else if (basicBean.isChangeCodeType()) {
            requestCode(MobileUtils.getCodeType(getString(R.string.verify_code_change)));
            countDown();
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    /**
     * 倒计时
     */
    private void countDown() {
        new Thread(new Runnable() {
            int time = 60;

            @Override
            public void run() {
                for (int i = time; i > 0; i--) {
                    if (i > 0) {
                        try {
                            if (codeHandler != null) {
                                codeHandler.sendMessage(Message.obtain(codeHandler,
                                        GET_VALIDATION_TIME, i));
                                Thread.sleep(1000);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (codeHandler != null) {
                    codeHandler.sendMessage(Message.obtain(codeHandler,
                            GET_VALIDATION_TIME_OUT, time));
                }
            }
        }).start();
    }

    private class MyHandler extends Handler {

        private final WeakReference<ForgetPsdNextActivity> mActivity;

        private MyHandler(ForgetPsdNextActivity forgetPsdNextActivity) {
            this.mActivity = new WeakReference<>(forgetPsdNextActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            ForgetPsdNextActivity mInstance = mActivity.get();
            if (mInstance == null){
                return;
            }
            super.handleMessage(msg);
            int result = (Integer) msg.obj;
            switch (msg.what) {

                case GET_VALIDATION_TIME_OUT:
                    tvSendAgain.setEnabled(true);
                    tvSendAgain.setTextColor(ContextCompat.getColor(mInstance, R.color.send_again));
                    tvCountDown.setVisibility(View.GONE);
                    break;

                case GET_VALIDATION_TIME:
                    tvSendAgain.setEnabled(false);
                    tvSendAgain.setTextColor(ContextCompat.getColor(mInstance, R.color.hint_color));
                    tvCountDown.setVisibility(View.VISIBLE);
                    tvCountDown.setText(new StringBuilder().append(result).append("s后"));
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // i null, all callbacks and messages will be removed
        codeHandler.removeCallbacksAndMessages(null);
    }
}
